package com.sjx.onelinecord.socket

import android.app.Service
import android.content.Intent
import android.os.IBinder
import java.io.*
import java.net.ServerSocket
import java.net.Socket
import java.util.*

class TCPServerService : Service() {
    private var mIsServiceDestroyed = false
    private val mDefinedMessages = arrayOf(
            "hello，小妹妹",
            "你好，妹妹",
            "你好，可以加个微信吗?",
            "你好，可以加个微信吗?",
            "你好，可以加个微信吗?")

    override fun onCreate() {
        Thread(TcpServer()).start()
        super.onCreate()
    }

    override fun onDestroy() {
        mIsServiceDestroyed = true
        super.onDestroy()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    private inner class TcpServer : Runnable {
        override fun run() {
            var serverSocket: ServerSocket? = null
            serverSocket = try {
                ServerSocket(8688)
            } catch (e: IOException) {
                println("establish tcp server failed,port : 8688")
                e.printStackTrace()
                return
            }
            while (!mIsServiceDestroyed) {
                //接受客户端请求
                try {
                    val client = serverSocket?.accept()
                    println("accept")
                    object : Thread() {
                        override fun run() {
                            try {
                                if (client != null) {
                                    responseClient(client)
                                }
                            } catch (e: IOException) {
                                e.printStackTrace()
                            }
                        }
                    }.start()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    /**
     * 知识巩固：
     * 1.input（输入/读取）；2。output（输出/写入）
     * 输入/读取：把硬盘中的数据，读取到内存中使用
     * 输出/写入：把内存中的数据，写入到硬盘中保存
     *
     * @param client
     * @throws IOException
     */
    @Throws(IOException::class)
    private fun responseClient(client: Socket) {
        //用于接受客户端消息
        //为了提高效率，在BufferedReader中包装InputStreamReader
        //InputStreamReader（从字节到字符的桥梁）
        //client.getInputStream得到的是客户端传输的字节，通过new InputStreamReader将其
        //转换为字符流，再通过BufferedReader包装提高效率，提高效率原因看csdn_Android收藏夹某博客
        val `in` = BufferedReader(InputStreamReader(
                client.getInputStream()
        ))
        //用于向客户端发送消息
        val out = PrintWriter(BufferedWriter(
                OutputStreamWriter(client.getOutputStream())
        ), true)
        out.println("Welcome to the ChatRoom")
        while (!mIsServiceDestroyed) {
            //BufferedReader（字符缓冲输入流）特有成员方法readLine（）读取一个文本行，读取一行数据
            val str = `in`.readLine()
            println("msg from client:$str")
            if (str == null) {
                //客户端断开连接
                break
            }
            val i = Random().nextInt(mDefinedMessages.size)
            val msg = mDefinedMessages[i]
            out.println(msg)
            println("send : $msg")
        }
        println("client quit")
        //关闭流
        out.close()
        `in`.close()
        client.close()
    }
}